<?php
// $Id: 

/**
 * @file
 * S-gas employee administration UI.
 */

/*================= sg_employee admin functions===============*/

//none

/*================= sg_employee admin functions end===============*/




/*================= sg_employee list functions===============*/

/**
 * A custom theme function.
 *
 * By using this function to format our node-specific information, themes
 * can override this presentation if they wish. We also wrap the default
 * presentation in a CSS class that is prefixed by the module name. This
 * way, style sheets can modify the output without requiring theme code.
 */
function theme_sg_employee_basic_info($node) {
  $id_types = sg_employee_get_id_types();
  foreach ($id_types as $id){
    if($id[$node->sg_employee_id_type]){
      $id_type = $id[$node->sg_employee_id_type];
    }
  } 
  $gender = $node->sg_employee_gender ? t('Male') : t('Female'); 
  $check_attendance = $node->sg_employee_check_attendance ? t('Yes') : t('No');
  $working = $node->sg_employee_working ? t('Working') : t('Left');

  $output = '<div class="sg_employee_basic_info">';
  $output .= '<div>'.t("Employee's name").":".check_plain($node->sg_employee_name).'</div>';
  $output .= '<div>'.t("Employee's ID type").":".$id_type.'</div>';
  $output .= '<div>'.t("Employee's ID number").":".check_plain($node->sg_employee_id_number).'</div>';
  $output .= '<div>'.t("Gender").":".$gender.'</div>';
  $output .= '<div>'.t("Birthday").":".$node->sg_employee_birthday.'</div>';
  $output .= '<div>'.t("Whether the employee's attendance needs to be checked").":".$check_attendance.'</div>';
  $output .= '<div>'.t("Employee's working status in this company").":".$working.'</div>';
  if(!$node->sg_employee_working){
    $output .= '<div>'.t("Date of leaving the company").":".$node->sg_employee_leaving_date.'</div>';
  }
  $output .= '</div>';
  return $output;
}

function _sg_employee_get_update_fields(){
  $fields = array();
//  $fields['sg_employee_eid'] = t('Employee number');
  $fields['sg_employee_ename'] = t("Employee's name");
  $fields['sg_employee_id_number'] = t("Employee's ID number");
  $fields['sg_employee_gender'] = t('Gender');
  $fields['sg_employee_birthday'] = t('Birthday');
  $fields['sg_employee_department'] = t('Department');
  $fields['sg_employee_check_attendance'] = t('Attendance');
  $fields['sg_employee_leaving_date'] = t('Leaving date');
  return $fields;
}


function sg_employee_nodes_update_submit($form, &$form_state){
//      print_r($form_state);
  $field = $form_state['values']['field'];
  $field_value = $form_state['values']['field_value'];
  $nodes = array_filter($form_state['values']['nodes']);
  foreach ($nodes as $nid){
    $node = node_load($nid);
    $node->$field = $field_value;
    $node->sg_employee_birthday_ddate = _sg_employee_date_mysql_to_drupal($node->sg_employee_birthday);
    $node->sg_employee_leaving_ddate = _sg_employee_date_mysql_to_drupal($node->sg_employee_leaving_date);
    sg_employee_update($node);
  }
  if(!$nodes) {drupal_set_message(t("No record selected, please select one or more records."));}
}

function _sg_employee_id_number_to_birthday($id_number){
  $len = strlen($id_number);
  switch($len){
  case 18:
    $date['year'] = substr($id_number, 6, 4);
    $date['month'] = substr($id_number, 10, 2);
    $date['day'] = substr($id_number, 12, 2);
    $birthday = _sg_employee_date_drupal_to_mysql($date);
    break;
  case 15:
    $date['year'] = '19'.substr($id_number, 6, 2);
    $date['month'] = substr($id_number, 8, 2);
    $date['day'] = substr($id_number, 10, 2);
    $birthday = _sg_employee_date_drupal_to_mysql($date);
    break;
  default:
    $birthday='0000-00-00';
    break;
  }
  return $birthday;
}
  

function sg_employee_nodes_update_birthday_submit($form, &$form_state){
//      print_r($form_state);
  $field = $form_state['values']['field'];
  $field_value = $form_state['values']['field_value'];
  $nodes = array_filter($form_state['values']['nodes']);
  foreach ($nodes as $nid){
    $node = node_load($nid);
    $node->sg_employee_birthday = _sg_employee_id_number_to_birthday($node->sg_employee_id_number);
    $node->sg_employee_birthday_ddate = _sg_employee_date_mysql_to_drupal($node->sg_employee_birthday);
    $node->sg_employee_leaving_ddate = _sg_employee_date_mysql_to_drupal($node->sg_employee_leaving_date);
    sg_employee_update($node);
  }
  if(!$nodes) {drupal_set_message(t("No record selected, please select one or more records."));}
}



function sg_employee_nodes_id_type_update_submit($form, &$form_state){
  // Filter out unchecked nodes
  $nodes = array_filter($form_state['values']['nodes']);
//  $operation = $form_state['values']['update_id_type'];
  foreach ($nodes as $nid){
    $node = node_load($nid);
    $node->sg_employee_id_type = $form_state['values']['id_type'];;
    sg_employee_update($node);
  }
}

function sg_employee_nodes_working_update_submit($form, &$form_state){
  // Filter out unchecked nodes
  $nodes = array_filter($form_state['values']['nodes']);
  foreach ($nodes as $nid){
    $node = node_load($nid);
    $node->sg_employee_working = $form_state['values']['working'];;
    sg_employee_update($node);
  }
}


/**
 * Menu callback: employee list.
 */
function sg_employee_list($form_state) {

  $form['list'] = sg_employees_ui($form_state);
  return $form;
}

/**
 * Form builder: Builds the sg_employee list overview.
 */
function sg_employees_ui($form_state) {

  $form['options'] = array(
    '#type' => 'fieldset',
    '#title' => t('For the selected employees'),
    '#prefix' => '<div class="container-inline">',
  );

  $id_options = sg_id_get_id_types();

  $form['options']['id_type'] = array(
    '#type' => 'select',
    '#title' => t('Update ID type to'),
    '#options' => $id_options,
    '#default_value' => '0',
    '#prefix' => '<p>',
  );
  $form['options']['update_id_type'] = array(
    '#type' => 'submit',
    '#value' => t('Update'),
    '#submit' => array('sg_employee_nodes_id_type_update_submit'),
    '#suffix' => '</p>',
  );

  $form['options']['working_status'] = array(
    '#type' => 'select',
    '#title' => t('Update working status to'),
    '#options' => array(0=>t('Working'),1=>t('Left')),
    '#default_value' => '0',
    '#prefix' => '<p>',
  );

  $form['options']['update_working_status'] = array(
    '#type' => 'submit',
    '#value' => t('Update'),
    '#submit' => array('sg_employee_nodes_working_update_submit'),
    '#suffix' => '</p>',
  );

  $employee_field_options = _sg_employee_get_update_fields();

  $form['options']['field'] = array(
    '#type' => 'select',
    '#title' => t('Update field'),
    '#options' => $employee_field_options,
    '#default_value' => '0',
    '#prefix' => '<p>',
  );

  $form['options']['field_value'] = array(
    '#type' => 'textfield',
    '#title' => t('Update field value to'),
    '#default_value' => '0',
  );

  $form['options']['update_field_submit'] = array(
    '#type' => 'submit',
    '#value' => t('Update'),
    '#submit' => array('sg_employee_nodes_update_submit'),
    '#suffix' => '</p>',
  );

  $form['options']['update_birthday_by_id_submit'] = array(
    '#type' => 'submit',
    '#value' => t('Update birthday by ID'),
    '#submit' => array('sg_employee_nodes_update_birthday_submit'),
    '#suffix' => '</div>',
  );



  $destination = drupal_get_destination();

  $filter['join'] = 'INNER JOIN {sg_employee} e ON n.vid = e.vid LEFT JOIN {sg_id} i on e.id_type = i.id_type';
  $filter['where'] = "WHERE n.type = 'sg_employee'";
  $filter['args'] = '';
  $query ='SELECT n.*, u.name as uname, e.eid as sg_employee_eid, e.name as sg_employee_ename, i.id_name as sg_employee_id_name, e.id_number as sg_employee_id_number, e.gender as sg_employee_gender, e.birthday as sg_employee_birthday, e.department as sg_employee_department, e.check_attendance as sg_employee_check_attendance, e.working as sg_employee_working, e.leaving_date as sg_employee_leaving_date '
    .'FROM {node} n '. $filter['join'] .' INNER JOIN {users} u ON n.uid = u.uid '. $filter['where'] .' ORDER BY e.eid ASC';
  
  $result = pager_query(db_rewrite_sql($query), 50, 0, NULL, $filter['args']);
  $nodes = array();

  while ($node = db_fetch_object($result)) {
    $nodes[$node->nid] = '';
    $options = array();
    switch($node->sg_employee_department){
    case SG_DEPARTMENT_PRODUCTIVE:
      $department = t('Productive department');
      break;
    case SG_DEPARTMENT_SALES:
      $department = t('Sales department');
      break;
    case SG_DEPARTMENT_MANAGERIAL:
    default:
      $department = t('Managerial department');
      break;
    }

    $form['sg_employee_eid'][$node->nid] =  array('#value' => $node->sg_employee_eid);
    $form['sg_employee_ename'][$node->nid] =  array('#value' => $node->sg_employee_ename);
    $form['sg_employee_id_name'][$node->nid] =  array('#value' => $node->sg_employee_id_name);
    $form['sg_employee_id_number'][$node->nid] =  array('#value' => $node->sg_employee_id_number);
    $form['sg_employee_gender'][$node->nid] =  array('#value' => $node->sg_employee_gender ? t('Male') : t('Female') );
    $form['sg_employee_birthday'][$node->nid] =  array('#value' => $node->sg_employee_birthday);
    $form['sg_employee_department'][$node->nid] =  array('#value' => $department);
    $form['sg_employee_check_attendance'][$node->nid] =  array('#value' => $node->sg_employee_check_attendance ? t('Yes') : t('No') );
    $form['sg_employee_working'][$node->nid] =  array('#value' => $node->sg_employee_working ? t('Working') : t('Left') );
    $form['sg_employee_leaving_date'][$node->nid] =  array('#value' => $node->sg_employee_leaving_date);
    $form['operations'][$node->nid] = array('#value' => l(t('edit'), 'node/'. $node->nid .'/edit', array('query' => $destination)));
  }
  $form['nodes'] = array('#type' => 'checkboxes', '#options' => $nodes);
  $form['pager'] = array('#value' => theme('pager', NULL, 50, 0));
  $form['#theme'] = 'sg_employee_nodes';
  return $form;
}

/**
 * Theme sg_employee nodes administration overview.
 *
 * @ingroup themeable
 */
function theme_sg_employee_nodes($form) {

  // If there are rows in this form, then $form['sg_employee_eid'] contains a list of
  // the employee-id form elements.
  $has_posts = isset($form['sg_employee_eid']) && is_array($form['sg_employee_eid']);
  
  $select_header = $has_posts ? theme('table_select_header_cell') : '';

  $header = array($select_header);
  
  $header[] = t('employee id');
  $header[] = t('employee name');
  $header[] = t('employee id name');
  $header[] = t('employee id number');
  $header[] = t('Gender');
  $header[] = t('Birthday');
  $header[] = t('Department');
  $header[] = t('Check attendance');
  $header[] = t('Status');
  $header[] = t('Left date');
  $header[] = t('Operations');
  $output = '';

  $output .= drupal_render($form['options']);
  if ($has_posts) {
    foreach (element_children($form['sg_employee_eid']) as $key) {
      $row = array();
      $row[] = drupal_render($form['nodes'][$key]);
      $row[] = drupal_render($form['sg_employee_eid'][$key]);
      $row[] = drupal_render($form['sg_employee_ename'][$key]);
      $row[] = drupal_render($form['sg_employee_id_name'][$key]);
      $row[] = drupal_render($form['sg_employee_id_number'][$key]);
      $row[] = drupal_render($form['sg_employee_gender'][$key]);
      $row[] = drupal_render($form['sg_employee_birthday'][$key]);
      $row[] = drupal_render($form['sg_employee_department'][$key]);
      $row[] = drupal_render($form['sg_employee_check_attendance'][$key]);
      $row[] = drupal_render($form['sg_employee_working'][$key]);
      $row[] = drupal_render($form['sg_employee_leaving_date'][$key]);
      $row[] = drupal_render($form['operations'][$key]);
      $rows[] = $row;
    }

  }
  else {
    $rows[] = array(array('data' => t('No posts available.'), 'colspan' => '12'));
  }

  $output .= theme('table', $header, $rows);
  if ($form['pager']['#value']) {
    $output .= drupal_render($form['pager']);
  }

  $output .= drupal_render($form);

  return $output;
}

/*================= sg_employee list functions end===============*/




/*================= sg_employee_salary admin functions===============*/

function sg_employee_create_salaries($from, $to, $employees, $previous_data) {
//  $month = format_date(time(), 'custom', 'm');
  $num=0;
  foreach($employees as $e){
    _sg_employee_create_salary($from, $to, $e, $previous_data);
    $num++;
  }
  drupal_set_message(format_plural($num, '1 node created.', '@count nodes created.'));
}

function _sg_employee_create_salary($from, $to, $e, $previous_data) {
    // Insert new data:
    $node->type = 'sg_salary';
    require_once './modules/node/node.pages.inc';
    node_object_prepare($node);
    $node->uid = 1;
    unset($node->nid);
    unset($node->vid);

    $node->title = $to." ".t('salary')." - ".$e->sg_employee_ename;
    $node->body = '';
    $node->teaser = node_teaser($node->body);
    $node->filter = variable_get('filter_default_format', 1);
    $node->format = FILTER_FORMAT_DEFAULT;
    $node->language = '';
    $node->revision = 1;
    $node->promote = 0;
    $node->created = time();
    
//      if ($add_terms) {
//        devel_generate_add_terms($node);
//      }  
    
    // Populate any sg_employee fields in the node
    _sg_employee_salary_generate_fields($node, $from, $to, $e, $previous_data);

    // Save the node:
    node_save($node);
      
    unset($node);
}

function _sg_employee_salary_generate_fields(&$node, $from, $to, $e, $previous_data){
  $node->sg_employee_eid = $e->sg_employee_eid;
  $node->sg_employee_salary_from_ddate = _sg_employee_date_mysql_to_drupal($from);  //using the drupal_date array format
  $node->sg_employee_salary_to_ddate = _sg_employee_date_mysql_to_drupal($to);      //to simulate a form submit

  if ($previous_data ==0){//use blank records
    $node->sg_employee_salary_base = 0; 
    $node->sg_employee_salary_housing_fund = 0; 
    $node->sg_employee_salary_pension_insurance = 0; 
    $node->sg_employee_salary_medical_insurance = 0;
    $node->sg_employee_salary_unemployment_insurance = 0; 
    $node->sg_employee_salary_attendance = 0;
    $node->sg_employee_salary_bonus = 0;
    $node->sg_employee_salary_floating = 0;
    $node->sg_employee_salary_sum = 0;
    $node->sg_employee_salary_tax = 0;
    $node->sg_employee_salary_after_tax = 0;
    $node->sg_employee_salary_bank = 0;
    $node->sg_employee_salary_account_number = 0; 
  }else{//get from last period
    $current = $node->sg_employee_salary_from_ddate; // we only use the month so day doesn't matter
    $previous = _sg_employee_salary_get_previous_by_eid($e->sg_employee_eid, $current);    
    if(!empty($preivous)){
      $node->sg_employee_salary_base = 0; 
      $node->sg_employee_salary_housing_fund = 0; 
      $node->sg_employee_salary_pension_insurance = 0; 
      $node->sg_employee_salary_medical_insurance = 0;
      $node->sg_employee_salary_unemployment_insurance = 0; 
      $node->sg_employee_salary_attendance = 0;
      $node->sg_employee_salary_bonus = 0;
      $node->sg_employee_salary_floating = 0;
      $node->sg_employee_salary_sum = 0;
      $node->sg_employee_salary_tax = 0;
      $node->sg_employee_salary_after_tax = 0;
      $node->sg_employee_salary_bank = 0;
      $node->sg_employee_salary_account_number = 0; 
    }else{
      $node->sg_employee_salary_base = $previous->sg_employee_salary_base; 
      $node->sg_employee_salary_housing_fund = $previous->sg_employee_salary_housing_fund; 
      $node->sg_employee_salary_pension_insurance = $previous->sg_employee_salary_pension_insurance; 
      $node->sg_employee_salary_medical_insurance = $previous->sg_employee_salary_medical_insurance;
      $node->sg_employee_salary_unemployment_insurance = $previous->sg_employee_salary_unemployment_insurance; 
      $node->sg_employee_salary_attendance = 0;
      $node->sg_employee_salary_bonus = $previous->sg_employee_salary_bonus;
      $node->sg_employee_salary_floating = 0;
      $node->sg_employee_salary_sum = 0;
      $node->sg_employee_salary_tax = 0;
      $node->sg_employee_salary_after_tax = 0;

      $node->sg_employee_salary_bank = $previous->sg_employee_salary_bank;
      $node->sg_employee_salary_account_number = $previous->sg_employee_salary_account_number; 
    }
  }
//  print_r($node);
}

function _sg_employee_salary_get_previous_by_eid($eid, $current){
  $pre = _sg_employee_get_previous_month($current);
  $from = $pre['year'].'-'.$pre['month'].'-'.'01';

  $lastday = _sg_employee_get_number_of_days_of_a_month($pre['month'],$pre['year']);
  $to = $pre['year'].'-'.$pre['month'].'-'.$lastday;

  $query ="SELECT s.eid as sg_employee_eid, s.base as sg_employee_salary_base, s.housing_fund as sg_employee_salary_housing_fund,
      s.pension_insurance as sg_employee_salary_pension_insurance, s.medical_insurance as sg_employee_salary_medical_insurance,
      s.unemployment_insurance as sg_employee_salary_unemployment_insurance, s.attendance as sg_employee_salary_attendance, 
      s.bonus as sg_employee_salary_bonus, s.floating as sg_employee_salary_floating,  s.sum as sg_employee_salary_sum, 
      s.tax as sg_employee_salary_tax, s.after_tax as sg_employee_salary_after_tax,
      s.bank as sg_employee_salary_bank, s.account_number as sg_employee_salary_account_number
      FROM {sg_salary} s WHERE s.eid = %d AND s.from = '".$from."'AND s.to = '".$to."' ORDER BY s.to LIMIT 1";
  $result = db_query($query, $eid);
  if (!$result) {return array();}
  $s = db_fetch_object($result);
  return $s;
}


function _sg_employee_salary_get_fields($eid, $from, $to){
  $query ="SELECT n.*, e.eid as sg_employee_eid, e.name as sg_employee_ename, s.*
    FROM {node} n INNER JOIN {sg_employee} e ON n.vid = e.vid LEFT JOIN {sg_salary} s WHERE e.eid = s.eid 
    WHERE e.eid = %d AND s.from = '%s' AND s.to = '%s' LIMIT 1";
  $result = db_query($query, $eid, $from, $to);
  if (!$result) {return array();}
  $s = db_fetch_object($result);
  return $s;
}

function sg_employee_create_payrolls_form($form_state){
// query to get all existing payrolls
  
// options for generating new payrolls
  $form['period'] = array(
    '#type' => 'fieldset',
    '#title' => t('Create empty payroll(s) for the following period'),
    '#prefix' => '<div class="container-inline">',
    '#suffix' => '</div>',
  );
  
  $date = getdate();
  $month = $date[mon]; // month is the English name, mon is numerical
  $year = $date[year];
  $lastday = _sg_employee_get_number_of_days_of_a_month($month,$year);

  $form['period']['from'] = array(
    '#type' => 'date',
    '#title' => t('From date'),
    '#default_value' => array('year'=>$year, 'month'=>$month, 'day'=>'1'),
    '#required' => $field->required,
  );

  $form['period']['to'] = array(
    '#type' => 'date',
    '#title' => t('To date'),
    '#default_value' => array('year'=>$year, 'month'=>$month, 'day'=>$lastday),
    '#required' => $field->required,
  );

  $form['employee'] = array(
    '#type' => 'fieldset',
    '#title' => t('For the following employee(s)'),
    '#prefix' => '<div class="container-inline">',
    '#suffix' => '</div>',
  );

  $form['employee']['choices'] = array(
    '#type' => 'radios',
    '#default_value' => 2,
    '#options' => array( 0 => t('Everyone'), 1 => t('Working'), 2 => t('Selected') ),
  );

  $options = array();
  $employees = sg_employee_get_employees();
  foreach($employees as $e){
    $options[$e->sg_employee_eid] = $e->sg_employee_ename;
  }

  $form['employee']['employee_list'] = array(
    '#type' => 'select',
    '#default_value' => 0,
    '#options' => $options,
  );

  $form['data']= array(
    '#type' => 'radios',
    '#title' => t('Filling with'),
    '#default_value' => 1,
    '#options' => array( 0 => t('Blank record'), 1 => t('Data from last working period') ),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Create'),
    '#submit' => array('sg_employee_create_payroll_submit'),
  );

  return $form;
}


function sg_employee_create_payroll_submit($form, &$form_state){
  // Filter out unchecked nodes
  $from = sprintf("%04d-%02d-%02d", $form_state['values']['from']['year'], $form_state['values']['from']['month'], $form_state['values']['from']['day']);
  $to = sprintf("%04d-%02d-%02d", $form_state['values']['to']['year'], $form_state['values']['to']['month'], $form_state['values']['to']['day']);
//  print("from $from to $to");
  //  print_r($form_state['values']);
  switch($form_state['values']['choices']){
  case 0:
    $employees = sg_employee_get_employees();
    break;   
  case 1:
    $employees = sg_employee_get_employees(' AND e.working = 1 ');
    break;
  case 2:
    $employees = sg_employee_get_employees(" AND e.eid = '".$form_state['values']['employee_list']."' "); 
    break;
  }
  sg_employee_create_salaries($from, $to, $employees, $form_state['values']['data']);
}

/*================= sg_employee_salary admin functions end===============*/



/*================= sg_employee_salary list functions===============*/

/**
 * Menu callback: employee salary list.
 */
function sg_employee_salary_list($form_state) {
  $form['filters'] = sg_employee_salary_list_filter_form($form_state);
  $form['list'] = sg_employees_salary_ui($form_state);
  return $form;
}

function _sg_employee_salary_get_existing_periods(){
  $query = "SELECT DISTINCT(`to`) FROM {sg_salary} WHERE 1";
  $result = db_query($query);
  while ($row = db_fetch_object($result)) {
    $dates[$row->to] = $row->to;
  }
  return $dates;
}

function _sg_employee_salary_get_update_fields(){
  $fields = array();
//  $fields['sg_employee_salary_from'] =  t('From date ');
//  $fields['sg_employee_salary_to'] = t('To date ');
//  $fields['sg_employee_eid'] = t('Employee number');
  $fields['sg_employee_salary_base'] = t('Base salary');
  $fields['sg_employee_salary_housing_fund'] = t('Housing fund');
  $fields['sg_employee_salary_pension_insurance'] = t('Pension insurance');
  $fields['sg_employee_salary_medical_insurance'] = t('Medical insurance');
  $fields['sg_employee_salary_unemployment_insurance'] = t('Unemployment insurance');
  $fields['sg_employee_salary_attendance'] = t('Attendance adjustment');
  $fields['sg_employee_salary_bonus'] = t('Bonus');
  $fields['sg_employee_salary_floating'] = t('Other floating');
//  $fields['sg_employee_salary_sum'] = t('Total salary before tax');
  $fields['sg_employee_salary_tax'] = t('Personal income tax');
//  $fields['sg_employee_salary_after_tax'] = t('Total salary after tax');
  $fields['sg_employee_salary_bank'] = t('Bank name');
  $fields['sg_employee_salary_account_number'] = t('Bank account number');
  return $fields;
}

function sg_employee_salary_filters() {
  // Regular filters
  if ($_SESSION['sg_employee_salary_list_filter']['to']){
    $default_date = $_SESSION['sg_employee_salary_list_filter']['to'];
  }
  $default_working_status = is_null($_SESSION['sg_employee_salary_list_filter']['working']) ? 1 : $_SESSION['sg_employee_salary_list_filter']['working'];

  $filters['to'] = array(
    'title' => t('Period end at'),
    'options' => _sg_employee_salary_get_existing_periods(),
    'default_value' => $default_date,
  );

  $filters['working'] = array(
    'title' => t('Employee\'s working status in this company'),
    'options' => array(0=>t('Left'),1=>t('Working'), 2=>t('All')),
    'default_value' => $default_working_status,
  );

  return $filters;
}

function sg_employee_salary_list_filter_form_submit($form, &$form_state){
  //$_SESSION['sg_employee_salary_list_filter'];
//      print_r($form_state);
  switch ($form_state['values']['submit']) {
    case t('Select'):
      $to = $form_state['values']['to'];
      $_SESSION['sg_employee_salary_list_filter']['to'] = $to;
      $working = $form_state['values']['working'];
      $_SESSION['sg_employee_salary_list_filter']['working'] = $working;
    break;
  }  
}

function _sg_employee_salary_nodes_update_tax($nodes, $tax){
  foreach ($nodes as $nid){
    $salary = node_load($nid); 
    $employee = _sg_employee_get_all_by_eid($salary->sg_employee_eid);
    if($tax[$employee->sg_employee_id_number]){
      $salary->sg_employee_salary_tax = $tax[$employee->sg_employee_id_number];
      $benefits = $salary->sg_employee_salary_housing_fund + $salary->sg_employee_salary_pension_insurance + $salary->sg_employee_salary_medical_insurance + $salary->sg_employee_salary_unemployment_insurance;
      $salary->sg_employee_salary_after_tax = $salary->sg_employee_salary_sum - $benefits - $salary->sg_employee_salary_tax;
      $salary->sg_employee_salary_from_ddate = _sg_employee_date_mysql_to_drupal($salary->sg_employee_salary_from);
      $salary->sg_employee_salary_to_ddate = _sg_employee_date_mysql_to_drupal($salary->sg_employee_salary_to);
      sg_employee_update($salary);
    } 
  }
  if(!$nodes) {drupal_set_message(t("No record selected, please select one or more records."));}
}

function sg_employee_salary_nodes_update_submit($form, &$form_state){
//      print_r($form_state);
  $field = $form_state['values']['field'];
  $field_value = $form_state['values']['field_value'];
  $nodes = array_filter($form_state['values']['nodes']);
  foreach ($nodes as $nid){
    $node = node_load($nid);
    $node->$field = $field_value;
    $node->sg_employee_salary_from_ddate = _sg_employee_date_mysql_to_drupal($node->sg_employee_salary_from);
    $node->sg_employee_salary_to_ddate = _sg_employee_date_mysql_to_drupal($node->sg_employee_salary_to);
    sg_employee_update($node);
  }
  if(!$nodes) {drupal_set_message(t("No record selected, please select one or more records."));}
}


function sg_employee_salary_nodes_update_sum_submit($form, &$form_state){
//      print_r($form_state);
  $field = $form_state['values']['field'];
  $field_value = $form_state['values']['field_value'];
  $nodes = array_filter($form_state['values']['nodes']);
  foreach ($nodes as $nid){
    $node = node_load($nid);
    $node->sg_employee_salary_sum = _sg_employee_salary_sum($node);
    $benefits = $node->sg_employee_salary_housing_fund + $node->sg_employee_salary_pension_insurance + $node->sg_employee_salary_medical_insurance + $node->sg_employee_salary_unemployment_insurance;
    $node->sg_employee_salary_after_tax = $node->sg_employee_salary_sum - $benefits - $node->sg_employee_salary_tax;
    $node->sg_employee_salary_from_ddate = _sg_employee_date_mysql_to_drupal($node->sg_employee_salary_from);
    $node->sg_employee_salary_to_ddate = _sg_employee_date_mysql_to_drupal($node->sg_employee_salary_to);
    sg_employee_update($node);
  }
  if(!$nodes) {drupal_set_message(t("No record selected, please select one or more records."));}

}

function _sg_employee_page_transfer($source) {
  ob_end_clean();

  $header = 'Content-Type: text/html';
  drupal_set_header($header);  

  if ($source) {
    print $source;
  }
  else {
    drupal_not_found();
  }
  exit();
}

function _sg_employee_file_transfer($source, $title) {
  ob_end_clean();

  $header = 'Content-Type: text/plain';
  drupal_set_header($header);  

  $header = 'Content-disposition: attachment; filename='.$title.'.txt';
  drupal_set_header($header);  

  if ($source) {
    print $source;
  }
  else {
    drupal_not_found();
  }
  exit();
}

function sg_employee_salary_nodes_export_enames_submit($form,&$form_state){
  $file .= "";
  $file .= "\r\n";
  $nodes = array_filter($form_state['values']['nodes']);
  $count = 0;
  
//序号~~姓名~~证件类型~~证件号~~性别~~出生日期~~国家、地区~~开票标志~~申报方式~~职务~~地址~~调入调离~~备注~~邮政编码

//1~~杨遂平~~1~~321081194802017536~~1~~1948-02-01~~156~~0~~0~~~~上海市青浦区朱家角镇西洋淀村2号~~0~~0~~201713

  foreach ($nodes as $nid){
    $salary = node_load($nid);
    $employee = _sg_employee_get_all_by_eid($salary->sg_employee_eid);
    $line = '';
    $line .= $employee->sg_employee_eid; //eid : 1
    $line .= '~~';
    $line .= iconv("UTF-8","GB2312",$employee->sg_employee_ename); //ename : YSP
    $line .= '~~';
    $line .= '1'; //id_type : 1
    $line .= '~~';
    $line .= $employee->sg_employee_id_number; //id_number : 310XXXXXXXXX
    $line .= '~~';
    $line .= $employee->sg_employee_gender; //gender: 1 male 0 female
    $line .= '~~';
    $line .= $employee->sg_employee_birthday; //brithday : 19xx-xx-xx
    $line .= '~~';
    $line .= '156'; //country code : 156 for china
    $line .= '~~';
    $line .= '0'; //invoice sign : 0
    $line .= '~~';
    $line .= '0'; //reporting method : 0
    $line .= '~~';
    $line .= ''; //title
    $line .= '~~';
    $line .= iconv("UTF-8","GB2312",variable_get('sg_employee_salary_reporting_address', t('Shanghai'))); // contact address
    $line .= '~~';
    $line .= 0; // working/leave, for reporting to tax department 
    $line .= '~~';
    $line .= 0; // notes
    $line .= '~~';
    $line .= variable_get('sg_employee_salary_reporting_zip', '201713'); // post code

    $benefits = $salary->sg_employee_salary_housing_fund + $salary->sg_employee_salary_pension_insurance + $salary->sg_employee_salary_medical_insurance + $salary->sg_employee_salary_unemployment_insurance;
    $taxable_salary = $salary->sg_employee_salary_sum - $benefits;
    $tax_threshold = variable_get('sg_employee_salary_default_tax_threshold', 2000);
    
    if ( floatval($taxable_salary) > floatval($tax_threshold) ) { // only report taxable people
      $file .= $line."\r\n";
      $count++;
    }else{ 
      // do not report non-taxable people
    }

  }
  if(!$nodes) {
    drupal_set_message(t("No record selected, please select one or more records."));}
  else{
    drupal_set_message(format_plural($count, '1 record exported.', '@count records exported.'));
    _sg_employee_file_transfer($file,'员工');
  }

}

function sg_employee_salary_nodes_export_tax_submit($form, &$form_state){
  $file .= "";
  $file .= "\r\n";
  $nodes = array_filter($form_state['values']['nodes']);
  $count = 0;
  foreach ($nodes as $nid){
    $salary = node_load($nid);
    $employee = _sg_employee_get_all_by_eid($salary->sg_employee_eid);
  
    //  证件类型~~证件号~~所得项目~~含税标志~~所属期起~~所属期止~~天数~~收入额~~扣除额~~税额~~减免税额
    $line = '';
    $line .= '1'; //id_type : 1
    $line .= '~~';
    $line .= $employee->sg_employee_id_number; //id_number : 310XXXXXXXXX
    $line .= '~~';
    $line .= '010000';  //income type: 010000
    $line .= '~~';
    $line .= '1'; //tax sign : 1
    $line .= '~~';
    $line .= trim($salary->sg_employee_salary_from, '-'); // from: 20080401
    $line .= '~~';
    $line .= trim($salary->sg_employee_salary_to, '-'); // from: 20080401
    $line .= '~~';
  
    $from_time = strtotime($salary->sg_employee_salary_from);
    $to_time = strtotime($salary->sg_employee_salary_to);
    $period = round(($to_time - $from_time) / 3600 / 24) + 1 ; //in days, including the first day
    $line .= $period; //days : 30
    $line .= '~~';

    $benefits = $salary->sg_employee_salary_housing_fund + $salary->sg_employee_salary_pension_insurance + $salary->sg_employee_salary_medical_insurance + $salary->sg_employee_salary_unemployment_insurance;
    $taxable_salary = $salary->sg_employee_salary_sum - $benefits;
    $line .= $taxable_salary; //salary_sum_taxable : all salaries - benefits
    $line .= '~~';
    
    $tax_threshold = variable_get('sg_employee_salary_default_tax_threshold', 2000);
    $line .= $tax_threshold; // tax_threshold : 2000
    $line .= '~~';
    $line .= 0; // tax amount : unknown
    $line .= '~~';
    $line .= 0; // tax credit : 0
    $line .= '~~';
    
    if ( floatval($taxable_salary) > floatval($tax_threshold) ) { // only report taxable people
      $file .= $line."\r\n";
      $count++;
    }else{ 
      // do not report non-taxable people
    }
  }
  if(!$nodes) {
    drupal_set_message(t("No record selected, please select one or more records."));}
  else{
    drupal_set_message(format_plural($count, '1 record exported.', '@count records exported.'));
    _sg_employee_file_transfer($file, '工资');
  }
}

function sg_employee_salary_nodes_import_tax_submit($form, &$form_state){
  global $user;
  //$file = file_save_upload('import_tax_file');
  //TODO:
  //  print_r($_FILES);
  $tmp_path = $_FILES['import_tax_file']['tmp_name'];

  // Save file uploaded to buffer
  $lines = array();
  if ($user->uid != 1 || user_access('edit sg_salary')) {

    if ($fd = fopen($tmp_path, 'rb')) {
      while (!feof($fd)) {
        $lines[]=fgets($fd);
      }
      fclose($fd);
      file_delete($file->filepath);
    }
  }

  //证件类型~~证件号~~所得项目~~含税标志~~所属期起~~所属期止~~天数~~收入额~~扣除额~~税额~~减免税额

  //1~~321081194802017536~~010000~~1~~20080401~~20080430~~29~~2700~~2000~~45~~0

  foreach($lines as $line){
    $line = trim($line);
    if((!empty($line)) && (is_numeric($line[0]))){
      $fields = explode("~~",$line);
      $value->id_type = "".$fields[0];
      $value->id_number = "".$fields[1];
      $value->income_type = "".$fields[2];
      $value->tax_sign = "".$fields[3];
      $value->from = "".$fields[4];
      $value->to = "".$fields[5];
      $value->days = "".$fields[6];
      $value->taxable_income = "".$fields[7];
      $value->tax_threshold = "".$fields[8];
      $value->tax = "".$fields[9];
      $value->tax_credit = "".$fields[10];
      $tax[$value->id_number] = $value->tax;
    }
  }
  $nodes = array_filter($form_state['values']['nodes']);
  _sg_employee_salary_nodes_update_tax($nodes, $tax );
}

function _sg_employee_chinese_money($thenumber){
  $Money = 0;
  $i =0;
  $length = 0;
  $one = array ();  // number
  $onestr = array(); // number unit
  $String1 = "零壹贰叁肆伍陆柒捌玖";
  $String2 = "万仟佰拾亿仟佰拾万仟佰拾元角分厘毫";
  $checkp = strpos($thenumber,".");
  if ($checkp === FALSE) {
  }else{
    $thenumber=trim($thenumber,".");
  }
  $length=strlen($thenumber);
  for($i=0;$i<=$length-1; $i++){
    $one[$i]=mb_substr($thenumber,$i,1); 
    $one[$i]=mb_substr($String1,$one[$i],1); // change $one[$i] to Chinese
    if ($checkp==FALSE) { // no cents
      $onestr[$i]=mb_substr($String2,13-$length+$i,1);
      $one[$i]=$one[$i].$onestr[$i];
    }else{ //has cents
      if($i<$checkp){
        $onestr[$i] = mb_substr($String2,13-$length+$i+($length-$checkp),1);
        $one[$i]=$one[$i].$onestr[$i];
      }elseif($i==$checkp){
        unset($one[$i]);
      }else{
        $onestr[$i] = mb_substr($String2,12-$length+$i+($length-$checkp),1);
        $one[$i]=$one[$i].$onestr[$i];
      }
    }      
  }
  $Money=implode('',$one);
  //return $Money;
  $Money=str_replace('零元','元',$Money);
  $Money=str_replace('零万','万',$Money);
  $Money=str_replace('零亿','亿',$Money);
  $Money=str_replace('零仟','零',$Money);
  $Money=str_replace('零佰','零',$Money);
  $Money=str_replace('零拾','零',$Money);
  $Money=str_replace('零角','零',$Money);
  $Money=str_replace('零分','整',$Money);
  while(strpos($Money,'零零')!=FALSE){
    $Money=str_replace('零零','零',$Money);
  }
  $Money=str_replace('零元','元',$Money);
  $Money=str_replace('零整','整',$Money);

  if($checkp === FALSE){
    $Money .= '整';
  }
  return $Money;
}



function _sg_employee_salary_prepare_report($accounts, $style='bank_account'){
  $year = substr($accounts['date'], 0, 4);
  $month = substr($accounts['date'], 5, 2);
  $total = sprintf("%.2f", $accounts['total']);
  unset($accounts['total']);
  unset($accounts['date']);

  $i = 1;
  $count = sizeof($accounts);
  $page = "<html><body>\n";
  $page .= '<div style="margin-left:2em;">';
  $page .= '<div style="width:600px; text-align:center; margin-top:3em; margin-bottom:1em;">';
  $page .= "<strong>上海基量标准气体有限公司职工".$year."年".$month."月工资</strong>";
  $page .= "</div>\n";

  $page .= "<div><table border=1 width=600><tbody>\n";
  $page .= "<tr><th>序号</th><th>姓名</th>";
  if($style == 'bank_account'){
    $page .= "<th>账号</th>";
  }
  $page .= "<th>实发数</th></tr>\n";
  for($i=1; $i<=$count;$i++){
    $account = array_shift($accounts);
    $row = "<tr><td>".$i."</td><td>".$account['ename']."</td>";
    if($style == 'bank_account'){
      $row .= "<td>".$account['account_number']."</td>";
    }
    $row .= "<td>".sprintf("%8.2f",$account['amount'])."</td></tr>\n";
    $page .= $row;
  }
  $page .= "</tbody></table></div>";
   
  $page .= '<div style="width:600px;text-align:right;">';
  $page .= "总计:".$total; 
  $page .= "</div>\n";
  $page .= '<div style="width:600px;text-align:right;">';
  $page .= "人民币:"._sg_employee_chinese_money($total); 
  $page .= "</div>\n";
  $page .= '<div style="width:600px; text-align:center; margin-top:1em;">';
  $page .= '<table width=590 ><tbody><tr><td align=left>审核:</td><td align=center>批准:</td><td align=right>制表:杨一</td></tr></tbody></table>';
  $page .= "</div>\n";
  $page .= "</div>\n";

/* test cases
  $page .= "<div>";
  $page .= _sg_employee_chinese_money('10000.20'); 
  $page .= "</div>\n";
  $page .= "<div>";
  $page .= _sg_employee_chinese_money('100000'); 
  $page .= "</div>\n";
  $page .= "<div>";
  $page .= _sg_employee_chinese_money('10001'); 
  $page .= "</div>\n";
  $page .= "<div>";
  $page .= _sg_employee_chinese_money('12010.20'); 
  $page .= "</div>\n";
 */
  return $page;
}

function _sg_employee_salary_prepare_budget_report($date, $accounts){
  $year = substr($date, 0, 4);
  $month = substr($date, 5, 2);

  $i = 1;
  $count = sizeof($accounts);
  $page = "<html><body>\n";
  $page .= '<div style="margin-left:2em;">';
  $page .= '<div style="width:600px; text-align:center; margin-top:3em; margin-bottom:1em;">';
  $page .= "<strong>上海基量标准气体有限公司".$year."年".$month."月工资汇总表</strong>";
  $page .= "</div>\n";
  $page .= "<div>";
  $page .= "<table border=1 width=600><tbody>\n";
  $page .= "<tr>";
  $page .= "<th>部门</th>";
  $page .= "<th>工资</th>";
  $page .= "<th>所得税</th>";
  $page .= "<th>四金</th>";
  $page .= "</tr>\n";
  foreach($accounts as $a){
    if($a['name'] != t('Total')){
      $row = "<tr>";
      $row .= "<td>".$a['name']."</td>";
      $row .= "<td>".sprintf("%8.2f",$a['salary'])."</td>";
      $row .= "<td>".sprintf("%8.2f",$a['tax'])."</td>";
      $row .= "<td>".sprintf("%8.2f",$a['benefits'])."</td>";
      $row .= "</tr>\n";
      $page .= $row;
    }
  }
    $row = "<tr>";
    $row .= "<td>".$accounts['total']['name']."</td>";
    $row .= "<td>".sprintf("%8.2f",$accounts['total']['salary'])."</td>";
    $row .= "<td>".sprintf("%8.2f",$accounts['total']['tax'])."</td>";
    $row .= "<td>".sprintf("%8.2f",$accounts['total']['benefits'])."</td>";
    $row .= "</tr>\n";
    $page .= $row;

  $page .= "</tbody></table></div>";
   
  $page .= '<div style="width:600px; text-align:center; margin-top:1em;">';
  $page .= '<table width=590 ><tbody><tr><td align=left>审核:</td><td align=center>批准:</td><td align=right>制表:杨一</td></tr></tbody></table>';
  $page .= "</div>\n";

  $page .= "</div>\n";

  return $page;
}


function sg_employee_salary_bank_report_submit($form, &$form_state){
  $nodes = array_filter($form_state['values']['nodes']);
  $accounts = array();
  $accounts['total'] = 0; 
  foreach ($nodes as $nid){
    $node = node_load($nid);
    if (!$accounts['date']){
      $accounts['date'] = $node->sg_employee_salary_to;
    }

    if(intval($node->sg_employee_salary_account_number) == 0){
      //do nothing
    }elseif(strlen($node->sg_employee_salary_account_number) <=5 ){ //not really a bank account number, add to the eid
      $eid = $node->sg_employee_salary_account_number;
      $accounts[$eid]['amount'] += $node->sg_employee_salary_after_tax;
      $accounts['total'] += $node->sg_employee_salary_after_tax; //don't use 'amount', because it may contain several accounts
    }else{ // real account, setup the payment amount
      $accounts[$node->sg_employee_eid] = array();
      $accounts[$node->sg_employee_eid]['ename'] = _sg_employee_get_name_by_eid($node->sg_employee_eid);
      $accounts[$node->sg_employee_eid]['account_number'] = $node->sg_employee_salary_account_number;
      $accounts[$node->sg_employee_eid]['amount'] = $node->sg_employee_salary_after_tax;
      $accounts['total'] += $node->sg_employee_salary_after_tax;
    }
  }
  $output = _sg_employee_salary_prepare_report($accounts,'bank_account');
  if(!$nodes) {drupal_set_message(t("No record selected, please select one or more records."));}
  _sg_employee_page_transfer($output);
}

function sg_employee_salary_cash_report_submit($form, &$form_state){
  $nodes = array_filter($form_state['values']['nodes']);
  $accounts = array();
  $accounts['total'] = 0; 
  foreach ($nodes as $nid){
    $node = node_load($nid);
    if (!$accounts['date']){
      $accounts['date'] = $node->sg_employee_salary_to;
    }

    if((intval($node->sg_employee_salary_account_number) == 0)&& (floatval($node->sg_employee_salary_after_tax) - 0 > 0.01 )){
      //no bank account, pay cash 
      $accounts[$node->sg_employee_eid] = array();
      $accounts[$node->sg_employee_eid]['ename'] = _sg_employee_get_name_by_eid($node->sg_employee_eid);
      $accounts[$node->sg_employee_eid]['amount'] = $node->sg_employee_salary_after_tax;
      $accounts['total'] += $node->sg_employee_salary_after_tax;
    }
  }
  $output = _sg_employee_salary_prepare_report($accounts,'cash');
  if(!$nodes) {drupal_set_message(t("No record selected, please select one or more records."));}
  _sg_employee_page_transfer($output);
}

function sg_employee_salary_budget_report_submit($form, &$form_state){
  $nodes = array_filter($form_state['values']['nodes']);
  $accounts = array();
  $departments = array(SG_DEPARTMENT_MANAGERIAL => t('Managerial department'), SG_DEPARTMENT_PRODUCTIVE => t('Productive department'),SG_DEPARTMENT_SALES => t('Sales department'));
  foreach($departments as $dept=>$name){
    $accounts[$dept]['name'] = $name; 
    $accounts[$dept]['salary'] = 0; 
    $accounts[$dept]['tax'] = 0; 
    $accounts[$dept]['benefits'] = 0; 
  }
  $accounts['total']['name'] = t('Total'); 
  $accounts['total']['salary'] = 0; 
  $accounts['total']['tax'] = 0; 
  $accounts['total']['benefits'] = 0; 

  foreach ($nodes as $nid){
    $node = node_load($nid);
    if (!$date){
      $date = $node->sg_employee_salary_to;
    }
    
    $e=_sg_employee_get_all_by_eid($node->sg_employee_eid);
    $benefits = $node->sg_employee_salary_housing_fund + $node->sg_employee_salary_pension_insurance + $node->sg_employee_salary_medical_insurance + $node->sg_employee_salary_unemployment_insurance;

    $accounts[$e->sg_employee_department]['salary'] += $node->sg_employee_salary_after_tax;
    $accounts[$e->sg_employee_department]['tax'] += $node->sg_employee_salary_tax;
    $accounts[$e->sg_employee_department]['benefits'] += $benefits;

  }

  foreach($departments as $dept=>$name){
    $accounts['total']['salary'] += $accounts[$dept]['salary']; 
    $accounts['total']['tax'] += $accounts[$dept]['tax']; 
    $accounts['total']['benefits'] += $accounts[$dept]['benefits']; 
  }

  $output = _sg_employee_salary_prepare_budget_report($date, $accounts);
  if(!$nodes) {drupal_set_message(t("No record selected, please select one or more records."));}
  _sg_employee_page_transfer($output);
}

function sg_employee_salary_nodes_delete_submit($form, &$form_state){
//      print_r($form_state);
  $nodes = array_filter($form_state['values']['nodes']);
  foreach ($nodes as $nid){
    $node = node_load($nid);
    node_delete($nid);
  }
  if(!$nodes) {drupal_set_message(t("No record selected, please select one or more records."));}
}

function sg_employee_salary_list_filter_form($form_state){
  $session = &$_SESSION['sg_employee_salary_list_filter'];
  $session = is_array($session) ? $session : array();
  $filters = sg_employee_salary_filters();

  $form['filters'] = array(
    '#type' => 'fieldset',
    '#title' => t('Show only items where'),
    '#prefix' => '<div class="container-inline">',
    '#suffix' => '</div>',
  );
  $form['filters']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Select'),
    '#submit' => array('sg_employee_salary_list_filter_form_submit'),
  );

  foreach ($filters as $key => $filter) {
    $form['filters']['option'][$key] = array( '#type' => 'select', 
                                              '#title' => $filter['title'], 
                                              '#options' => $filter['options'],
                                              '#default_value' => $filter['default_value'],
                                            );
//    print_r($form['filters']['option'][$key]);
  }
  return $form['filters'];
}
function _sg_employee_salary_get_last_payment_date(){
  $query ="SELECT s.to as sg_employee_salary_to FROM {sg_salary} s WHERE 1 ORDER BY s.to DESC LIMIT 1";
  $result = db_query($query);
  if (!$result) { return '0000-00-00'; }
  $s = db_fetch_object($result);
  return $s->sg_employee_salary_to;
}

function sg_employees_salary_ui($form_state){
  $session =$_SESSION['sg_employee_salary_list_filter'];
  $session = is_array($session) ? $session : array();

  $filter['join'] = 'INNER JOIN {sg_salary} s ON n.vid = s.vid INNER JOIN {sg_employee} e ON s.eid = e.eid LEFT JOIN {sg_id} i on e.id_type = i.id_type ';
  $filter['where'] = "WHERE n.type = 'sg_salary' ";
  
  if(is_null($session['to'])){
    $last_date = _sg_employee_salary_get_last_payment_date();
    if($last_date != '0000-00-00'){ // 0000-00-00 means no records
      $filter['where'] .= "AND s.to = '".$last_date."' ";
    }
  }else{
    $filter['where'] .= "AND s.to = '%s' ";
  }
  
  if(is_null($session['working'])){
    $filter['where'] .= "AND e.working = 1 ";
  }else{
    switch($session['working']) {
    case 0:
      $filter['where'] .= "AND e.working = 0 ";
      break;
    case 1:
      $filter['where'] .= "AND e.working = 1 ";
      break;
    case 2:
      $filter['where'] .= "AND e.working IN (0,1) ";
      break;
    }
  }

  $filter['args'] = array();
  if ($session['to']) {
    $filter['args'][] = $session['to'];
  }

  $query ='SELECT n.*, e.eid as sg_employee_eid, e.name as sg_employee_ename, s.base as sg_employee_salary_base,
      s.housing_fund as sg_employee_salary_housing_fund,
      s.pension_insurance as sg_employee_salary_pension_insurance, s.medical_insurance as sg_employee_salary_medical_insurance,
      s.unemployment_insurance as sg_employee_salary_unemployment_insurance, s.attendance as sg_employee_salary_attendance, 
      s.bonus as sg_employee_salary_bonus, s.floating as sg_employee_salary_floating,  s.sum as sg_employee_salary_sum, 
      s.tax as sg_employee_salary_tax, s.after_tax as sg_employee_salary_after_tax,
      s.from as sg_employee_salary_from, s.to as sg_employee_salary_to,
      s.bank as sg_employee_salary_bank, s.account_number as sg_employee_salary_account_number '
    .'FROM {node} n '. $filter['join'] . $filter['where'] .' ORDER BY e.eid ASC';
//  print_r($query);
//  print_r($session);
//  $result = pager_query(db_rewrite_sql($query), 50, 0, NULL, $filter['args']);
  $result = db_query($query, $filter['args']); // don't use pager for easier select all

  // operation forms, may delete, update selected records
  $form['options'] = array(
    '#type' => 'fieldset',
    '#title' => t('For the selected records'),
    '#prefix' => '<div class="container-inline">',
    '#suffix' => '</div>',
  );
  $options = _sg_employee_salary_get_update_fields();

  $form['options']['field'] = array(
    '#type' => 'select',
    '#title' => t('Update field'),
    '#options' => $options,
    '#default_value' => '0',
    '#prefix' => '<p>',
  );

  $form['options']['field_value'] = array(
    '#type' => 'textfield',
    '#title' => t('Update field value to'),
    '#default_value' => '0',
  );

  $form['options']['update_field_submit'] = array(
    '#type' => 'submit',
    '#value' => t('Update'),
    '#submit' => array('sg_employee_salary_nodes_update_submit'),
    '#suffix' => '</p>',
  );

  $form['options']['update_salary_sum_submit'] = array(
    '#type' => 'submit',
    '#value' => t('Recalculate sum'),
    '#submit' => array('sg_employee_salary_nodes_update_sum_submit'),
    '#prefix' => '<p>',
  );

  $form['options']['export_enames_to_the_tax_software_submit'] = array(
    '#type' => 'submit',
    '#value' => t('Export employee names to the tax software'),
    '#submit' => array('sg_employee_salary_nodes_export_enames_submit'),
  );

  $form['options']['export_to_the_tax_software_submit'] = array(
    '#type' => 'submit',
    '#value' => t('Export salaries to the tax software'),
    '#submit' => array('sg_employee_salary_nodes_export_tax_submit'),
  );


  $form['options']['import_tax_file'] = array(
    '#type' => 'file',
    '#name' => 'import_tax_file',
    '#title' => t('Attach new file'),
    '#size' => 40,
    '#description' =>  t('The maximum upload size is %filesize. Only files with the following extensions may be uploaded: %extensions. ', 
                        array('%extensions' => '.txt', '%filesize' => variable_get('sg_employee_salary_import_size_default', 1024000))
                       ),
    );

  $form['options']['import_from_tax_software_submit'] = array(
      '#type' => 'submit',
      '#value' => t('Import from the tax software'),
      '#name' => 'attach',
      '#submit' => array('sg_employee_salary_nodes_import_tax_submit'),
      '#suffix' => '</p>',
    );

  $form['reports'] = array(
    '#type' => 'fieldset',
    '#prefix' => '<div class="container-inline">',
    '#suffix' => '</div>',
    );
  $form['reports']['bank_report_submit'] = array(
      '#type' => 'submit',
      '#value' => t('Generate bank report'),
      '#submit' => array('sg_employee_salary_bank_report_submit'),
    );

  $form['reports']['cash_report_submit'] = array(
      '#type' => 'submit',
      '#value' => t('Generate cash report'),
      '#submit' => array('sg_employee_salary_cash_report_submit'),
    );


  $form['reports']['budget_report_submit'] = array(
      '#type' => 'submit',
      '#value' => t('Generate budget summary report'),
      '#name' => 'attach',
      '#submit' => array('sg_employee_salary_budget_report_submit'),
    );

  $form['delete_submit'] = array(
    '#type' => 'submit',
//    '#disabled' => TRUE,
    '#value' => t('Delete selected records'),
    '#submit' => array('sg_employee_salary_nodes_delete_submit'),
    '#prefix' => '<div>',
    '#suffix' => '</div>',
  );

  $nodes = array();

  while ($node = db_fetch_object($result)) {
    $nodes[$node->nid] = '';
    $options = array();
    $form['sg_employee_eid'][$node->nid] =  array('#value' => $node->sg_employee_eid);
    $form['sg_employee_ename'][$node->nid] =  array('#value' => $node->sg_employee_ename);
    $form['sg_employee_salary_base'][$node->nid] =  array('#value' => $node->sg_employee_salary_base);
//    $form['sg_employee_salary_housing_fund'][$node->nid] =  array('#value' => $node->sg_employee_salary_housing_fund);
//    $form['sg_employee_salary_pension_insurance'][$node->nid] =  array('#value' => $node->sg_employee_salary_pension_insurance);
//    $form['sg_employee_salary_medical_insurance'][$node->nid] =  array('#value' => $node->sg_employee_salary_medical_insurance);
//    $form['sg_employee_salary_unemployment_insurance'][$node->nid] =  array('#value' => $node->sg_employee_salary_unemployment_insurance);
    $benefits = $node->sg_employee_salary_housing_fund + $node->sg_employee_salary_pension_insurance + $node->sg_employee_salary_medical_insurance + $node->sg_employee_salary_unemployment_insurance;
    $form['sg_employee_salary_benefits'][$node->nid] =  array('#value' => $benefits);

    $form['sg_employee_salary_attendance'][$node->nid] =  array('#value' => $node->sg_employee_salary_attendance);
    $form['sg_employee_salary_bonus'][$node->nid] =  array('#value' => $node->sg_employee_salary_bonus);
    $form['sg_employee_salary_floating'][$node->nid] =  array('#value' => $node->sg_employee_salary_floating);
    $form['sg_employee_salary_sum'][$node->nid] =  array('#value' => $node->sg_employee_salary_sum);
    $form['sg_employee_salary_tax'][$node->nid] =  array('#value' => $node->sg_employee_salary_tax);
    $form['sg_employee_salary_after_tax'][$node->nid] =  array('#value' => $node->sg_employee_salary_after_tax);
    $form['sg_employee_salary_bank'][$node->nid] =  array('#value' => $node->sg_employee_salary_bank);
    $form['sg_employee_salary_account_number'][$node->nid] =  array('#value' => $node->sg_employee_salary_account_number);
    $form['operations'][$node->nid] = array('#value' => l(t('edit'), 'node/'. $node->nid .'/edit', array('query' => $destination)));
  }
  $form['nodes'] = array('#type' => 'checkboxes', '#options' => $nodes);
  $form['pager'] = array('#value' => theme('pager', NULL, 50, 0));
  $form['#theme'] = 'sg_employee_salary_nodes';
  $form['#attributes']['enctype'] = 'multipart/form-data';
  return $form;
}

function theme_sg_employee_salary_info($node) {
  $output = '<div class="sg_employee_basic_info">';
//  $output .= '<div>'.$node->sg_employee_ename'</div>';
  $output .= '<div>'.t('From date ')." ".check_plain($node->sg_employee_salary_from)." ".t('To date ')." ".check_plain($node->sg_employee_salary_to).'</div>';
  $output .= '<div>'.t('Employee number')." ".check_plain($node->sg_employee_eid).'</div>';
  $output .= '<div>'.t('Base salary')." ".check_plain($node->sg_employee_salary_base).'</div>';
  $output .= '<div>'.t('Housing fund')." ".check_plain($node->sg_employee_salary_housing_fund).'</div>';
  $output .= '<div>'.t('Pension insurance')." ".check_plain($node->sg_employee_salary_pension_insurance).'</div>';
  $output .= '<div>'.t('Medical insurance')." ".check_plain($node->sg_employee_salary_medical_insurance).'</div>';
  $output .= '<div>'.t('Unemployment insurance')." ".check_plain($node->sg_employee_salary_unemployment_insurance).'</div>';
  $output .= '<div>'.t('Attendance adjustment')." ".check_plain($node->sg_employee_salary_attendance).'</div>';
  $output .= '<div>'.t('Bonus')." ".check_plain($node->sg_employee_salary_bonus).'</div>';
  $output .= '<div>'.t('Other floating')." ".check_plain($node->sg_employee_salary_floating).'</div>';
  $output .= '<div>'.t('Total salary before tax')." ".check_plain($node->sg_employee_salary_sum).'</div>';
  $output .= '<div>'.t('Personal income tax')." ".check_plain($node->sg_employee_salary_tax).'</div>';
  $output .= '<div>'.t('Total salary after tax')." ".check_plain($node->sg_employee_salary_after_tax).'</div>';
  $output .= '<div>'.t('Bank name')." ".check_plain($node->sg_employee_salary_bank).'</div>';
  $output .= '<div>'.t('Bank account number')." ".check_plain($node->sg_employee_salary_account_number).'</div>';
  $output .= '</div>';

  return $output;
}
/**
 * Theme sg_salary nodes administration overview.
 *
 * @ingroup themeable
 */
function theme_sg_employee_salary_nodes($form) {

  // If there are rows in this form, then $form['sg_employee_eid'] contains a list of
  // the employee-id form elements.
  $has_posts = isset($form['sg_employee_eid']) && is_array($form['sg_employee_eid']);
  
  $select_header = $has_posts ? theme('table_select_header_cell') : '';

  $header = array($select_header);
  
  $header[] = t('Employee number');
  $header[] = t('employee name');
  $header[] = t('Base salary');
//  $header[] = t('Housing fund');
//  $header[] = t('Pension insurance');
//  $header[] = t('Medical insurance');
//  $header[] = t('Unemployment insurance');
  $header[] = t('The four benefits');
  $header[] = t('Attendance adjustment');
  $header[] = t('Bonus');
  $header[] = t('Other floating');
  $header[] = t('Total salary before tax');
  $header[] = t('Personal income tax');
  $header[] = t('Total salary after tax');
  $header[] = t('Bank name');
  $header[] = t('Bank account number');
  $header[] = t('Operations');
  $output = '';

  $output .= drupal_render($form['options']);
  $output .= drupal_render($form['reports']);
  if ($has_posts) {
    foreach (element_children($form['sg_employee_eid']) as $key) {
      $row = array();
      $row[] = drupal_render($form['nodes'][$key]);
      $row[] = drupal_render($form['sg_employee_eid'][$key]);
      $row[] = drupal_render($form['sg_employee_ename'][$key]);
      $row[] = drupal_render($form['sg_employee_salary_base'][$key]);
//      $row[] = drupal_render($form['sg_employee_salary_housing_fund'][$key]);
//      $row[] = drupal_render($form['sg_employee_salary_pension_insurance'][$key]);
//      $row[] = drupal_render($form['sg_employee_salary_medical_insurance'][$key]);
//      $row[] = drupal_render($form['sg_employee_salary_unemployment_insurance'][$key]);
      $row[] = drupal_render($form['sg_employee_salary_benefits'][$key]);
      $row[] = drupal_render($form['sg_employee_salary_attendance'][$key]);
      $row[] = drupal_render($form['sg_employee_salary_bonus'][$key]);
      $row[] = drupal_render($form['sg_employee_salary_floating'][$key]);
      $row[] = drupal_render($form['sg_employee_salary_sum'][$key]);
      $row[] = drupal_render($form['sg_employee_salary_tax'][$key]);
      $row[] = drupal_render($form['sg_employee_salary_after_tax'][$key]);
      $row[] = drupal_render($form['sg_employee_salary_bank'][$key]);
      $row[] = drupal_render($form['sg_employee_salary_account_number'][$key]);
      $row[] = drupal_render($form['operations'][$key]);
      $rows[] = $row;
    }

  }
  else {
    $rows[] = array(array('data' => t('No posts available.'), 'colspan' => '17'));
  }

  $output .= theme('table', $header, $rows);
  if ($form['pager']['#value']) {
    $output .= drupal_render($form['pager']);
  }

  $output .= drupal_render($form);

  return $output;
}

/*================= sg_employee_salary list functions end===============*/


